<template>
  <div class="app-container">

    <!--    <el-button type="success" @click="exportVisitor" icon="el-icon-download">导出</el-button>-->
    <!--    条件-->

    <el-form v-show="showSearch" ref="searchForm" :inline="true" :model="formVisitors" class="demo-form-inline"
             size="small">
      <el-form-item label="小区">
        <el-select v-model="formVisitors.communityId" placeholder="请选择">
          <el-option
            v-for="item in community"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="访客姓名" prop="visitorName">
        <el-input v-model="formVisitors.visitorName" placeholder="请输入访客姓名"/>
      </el-form-item>
      <el-form-item label="访客手机号" prop="visitorPhoneNumber">
        <el-input v-model="formVisitors.visitorPhoneNumber" placeholder="请输入访客手机号"/>
      </el-form-item>

      <el-form-item label="到访时间" prop="visitorDate">
        <div class="block">

          <el-date-picker
            v-model="formVisitors.visitorDate"
            type="date"
            placeholder="选择日期"
            format="yyyy 年 MM 月 dd 日"
            value-format="yyyy-MM-dd"
          />
        </div>
      </el-form-item>
      <el-form-item size="mini">

        <el-button type="primary" icon="el-icon-search" @click="onSubmit(current, pageSize, visitors)">查询</el-button>
        <el-button icon="el-icon-refresh" @click="resetForm('searchForm')">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="exportVisitor"
        >导出
        </el-button>
      </el-col>
      <!--隐藏搜索+刷新-->
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="onSubmit"
      />
    </el-row>

    <el-table
      ref="multipleTable"
      :data="visitors"
      tooltip-effect="dark"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column
        type="selection"
        width="55"
      />

      <el-table-column
        label="序号"
        width="120"
        type="index"
        :index="indexMethod"
        align="center"
      />

      <el-table-column
        label="访客姓名"
        width="120"
      >
        <template slot-scope="scope">{{ scope.row.visitorName }}</template>
      </el-table-column>

      <el-table-column
        label="访客手机号"
        width="120"
      >
        <template slot-scope="scope">{{ scope.row.visitorPhoneNumber }}</template>
      </el-table-column>

      <el-table-column
        label="小区名称"
        width="120"
      >
        <template slot-scope="scope">{{ scope.row.communityName }}</template>
      </el-table-column>

      <el-table-column
        label="到访时间"
        width="200"
      >
        <template slot-scope="scope">{{ scope.row.visitorDate }}</template>
      </el-table-column>

      <el-table-column
        label="创建时间"
        width="200"
      >
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>

      <el-table-column label="状态" align="center" prop="status">

        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '通行中'?'':'danger'">{{ scope.row.status === '已过期'?'已过期':'通行中' }}</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="address"
        label="备注"
        show-overflow-tooltip
      >
        <template slot-scope="scope">{{ scope.row.remark }}</template>
      </el-table-column>

      <el-table-column label="操作">
        <template v-if="scope.row.roleId !== 1" slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDeleteOne(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改访客邀请 对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="访客姓名" prop="visitorName">
          <el-input v-model="form.visitorName" placeholder="请输入访客姓名"/>
        </el-form-item>
        <el-form-item label="访客电话" prop="visitorPhoneNumber">
          <el-input v-model="form.visitorPhoneNumber" placeholder="请输入访客手机号"/>
        </el-form-item>
        <el-form-item label="到访时间" prop="visitorDate">
          <el-date-picker
            v-model="form.visitorDate"
            clearable
            size="small"
            style="width: 200px"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择到访时间"
          />
        </el-form-item>
        <el-form-item label="创建人id" prop="createById"  v-if="title!=='新增'">
          <el-input   v-model="form.createById" placeholder="请输入创建人id"  :disabled="true"/>
        </el-form-item>
        <el-form-item label="openid" prop="createByOpenId" v-if="title!=='新增'">
          <el-input v-model="form.createByOpenId" placeholder="请输入创建人openid" :disabled="true"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <div class="block" style="text-align:center">
      <el-pagination
        :current-page="this.current"
        :page-sizes="[ 3, 6, 9,12]"
        :page-size="this.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="this.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>
</template>

<script>

  import {getToken} from "../../../utils/auth";

  export default {

    name: 'Visitor',
    data() {
      return {
        pickerOptions: {
          shortcuts: [{
            text: '今天',
            onClick(picker) {
              picker.$emit('pick', new Date())
            }
          }, {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24);
              picker.$emit('pick', date)
            }
          }, {
            text: '一周前',
            onClick(picker) {
              const date = new Date();
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
              picker.$emit('pick', date)
            }
          }]
        }, // 时间
        title: '',
        showSearch: true,

        total: 0, // 共多少条
        current: 0, // 当前页数
        pageSize: 3, // 分页大小


        formVisitors: {
          visitorId: '',
          communityId: '',
          visitorName: '',
          visitorPhoneNumber: '',
          visitorDate: '',
          createTime: '',
          updateBy: '',
          updateTime: '',
          remark: '',
          communityName: ''
        }, // 搜索类容

        visitors: [], // 表格数据
        status: '', // 状态

        form: {},
        // 对话框
        open: false,

        multipleSelection: [],
        community: [], // 选择框数据
        value: '',


      }
    }, created() {
      this.onSubmit(this.current, this.pageSize);
      this.communityAll()
    },
    methods: {
      //添加按钮
      handleAdd() {
        this.open = true;      //打开对话框
        this.title = '新增';
        this.reset();          //重置 对话框
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.open = true;
        this.title = '修改';
        this.form = row;
        // console.log(this.form)
        this.form = {
          visitorId: row.visitorId,
          visitorName: row.visitorName,
          visitorPhoneNumber: row.visitorPhoneNumber,
          visitorDate: row.visitorDate,
          createById: row.createById,
          createByOpenId: row.createByOpenId,
          remark: row.remark,
          createBy: row.createBy
        }
      },

      /** 提交按钮 */
      submitForm() {
        if (this.title === '新增') {
          this.axios({
            url: '/zyVisitor',
            method: 'post',
            data: this.form
          }).then(res => {
            if (res.data.data === 'ok') {
              this.$message.success('新增成功')
            } else {
              this.$message.error('新增失败')
            }
          });
        } else if (this.title === '修改') {
          this.axios({
            url: '/zyVisitor',
            method: 'put',
            data: this.form
          }).then(res => {
            if (res.data.data === 'ok') {
              this.$message.success('修改成功')
            } else {
              this.$message.error('修改失败')
            }
          });
        }


        this.open = false;
        this.onSubmit(this.current, this.pageSize, this.visitors)
      },

      // 取消按钮
      cancel() {
        this.open = false;
        this.reset()
      },

      // 表单重置
      reset() {
        this.form = {
          visitorId: null,
          visitorName: null,
          visitorPhoneNumber: null,
          visitorDate: null,
          createById: null,
          createByOpenId: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        }
      },


      // 删除
      async handleDeleteOne(row) {
        await this.axios.delete('/zyVisitor/' + row.visitorId).then(res => {
          if (res.data.data === 'ok') {
            this.$message.success('删除成功')
          } else {
            this.$message.error('删除失败')
          }
          const totalPage = Math.ceil((this.total - 1) / this.pageSize); // 总页数
          this.current = this.current > totalPage ? totalPage : this.current;
          this.current = this.current < 1 ? 1 : this.current
        });
        this.onSubmit(this.current, this.pageSize, this.visitors)
      },

      // 分页查询 +  模糊查询
      onSubmit(current, pageSize, visitors) {
        console.log('submit!');

        current = this.current;
        pageSize = this.pageSize;
        visitors = this.formVisitors;

        // visitors.communityName=this.value; //动态绑定小区名称

        this.axios({
          url: '/zyVisitor/?' + this.qs.stringify(visitors),
          methods: 'get',
          params: {
            current: current,
            pageSize: pageSize
          }
        }).then(res => {
          if (res.data.status === 'OK') {
            this.visitors = res.data.data.records;
            this.current = res.data.data.current;
            this.total = res.data.data.total;
            this.pageSize = res.data.data.size
          }


          this.visitors.forEach((item) => {
            // 时间差的毫秒数
            const dateDiff = new Date(this.nowTime).getTime() - new Date(item.visitorDate).getTime();

            // 当前年月日时分秒
            const yy = new Date().getFullYear();// 2022
            const mm = (new Date().getMonth() + 1) < 10 ? '0' + (new Date().getMonth() + 1) : new Date().getMonth() + 1;// 07
            const dd = new Date().getDate() < 10 ? '0' + new Date().getDate() : new Date().getDate();// 18
            this.nowTime = yy + '-' + mm + '-' + dd;

            // 计算出相差天数
            const dayDiff = Math.floor(dateDiff / (24 * 3600 * 1000));
            if (dayDiff > 1) {
              item['status'] = '已过期'
            } else {
              item['status'] = '通行中'
            }
          })
        })
      },
      // 查询小区
      communityAll() {
        this.axios({
          url: '/zyCommunity/listAll'
        }).then(res => {
          const list = res.data.data.map((item, index) => ({
            value: item.communityId,
            label: item.communityName
          }));
          this.community = list
        })
      },

      // 全选
      handleSelectionChange(val) {
        this.multipleSelection = val
      },

      // 完整版 点击切换页数
      handleSizeChange(size) {
        console.log(`每页 ${size} 条`);
        this.pageSize = size;
        this.onSubmit(this.current, this.pageSize)
      },
      handleCurrentChange(current) { // 点击    翻页
        console.log(`当前页: ${current}`);
        this.current = current;
        this.onSubmit(this.current, this.pageSize)
      },

      // 表单序号
      indexMethod(index) { // 序号
        index = (index + 1) + (this.current - 1) * this.pageSize;
        return index
      },

      // 导出
      exportVisitor() {
        console.log('这是导出');
        location.href = 'http://localhost:8080/zyVisitor/export?'+"&Authorization="+getToken()
      },

      // 重置表单数据
      resetForm(searchForm) {
        this.$refs[searchForm].resetFields();// 重置表单数据
        this.formVisitors.communityId = '' ;// 清空下拉框
        this.onSubmit(this.current, this.pageSize, this.visitors)
      }
    }

  }
</script>

<style scoped>

</style>
